package ocg.common.re.influx.Influx;

import ocg.common.re.influx.GatlingParser.GatlingCsvParser;
import ocg.common.re.influx.GatlingParser.SimulationContext;
import org.influxdb.InfluxDB;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenbo on 2018/2/24.
 */
public class Run {
    /**
     * 通过文件夹名称，找到当前时间最近的 simulation.log
     * @param path
     * @param fileName
     * @return
     * @throws FileNotFoundException
     */
    private static File getResourceFile(String path , String fileName ) throws FileNotFoundException {
        File file=new File(path);
        int pathSize = path.length ();
        long newdate;
        File[] tempList = file.listFiles();
        System.out.println("该目录下对象个数："+tempList.length);
        List<Long> date = new ArrayList <Long> (  );
        for (int i = 0; i < tempList.length; i++) {
//            if (tempList[i].isFile()) {
//                //读取某个文件夹下的所有文件
//                System.out.println("文件："+tempList[i]);
//            }
            if (tempList[i].isDirectory()) {
                //读取某个文件夹下的所有文件夹
                path = String.valueOf ( tempList[i] );

                if ( path.indexOf ( fileName ) != -1 ) {
                    String[] sim = path.substring ( pathSize ).split ( "-" );
                    date.add ( Long.valueOf ( sim[1] ) );
                }
            }
        }
        newdate = date.get ( 0 );
        for ( int i = 0 ; i < date.size () ; i++ ){

            if ( newdate < date.get ( i ) ) {

                newdate = date.get ( i );
            }
        }

        path = path.substring ( 0 , pathSize ) + fileName + "-" + newdate + "/simulation.log";

        System.out.println ( path );

        return new File ( path );
    }

    /**
     * 链接influxDB ， 解析 simulation.log ，写入数据
     * @param path
     * @param fileName
     * @throws IOException
     */
    public static void simulation( String path , String fileName ) throws IOException {
        InfluxDB influxDB = new InfluxdbBuilder ( "root" , "root" , "http://localhost:8086/" ).build ();

        GatlingCsvParser csvParser = new GatlingCsvParser ( getResourceFile( path , fileName ) );
        SimulationContext context = csvParser.csvParser ();

        GatlingInflux influx = new GatlingInflux ( influxDB );

        influx.httpDate ( context );

        influxDB.close ();
    }

}
